package com.nfzm.service.impl;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.nfzm.dao.NfzmArticlePicDao;
import com.nfzm.entity.ArticleVO;
import com.nfzm.entity.NfzmArticlePic;
import com.nfzm.service.NfzmTermService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.UnsupportedMimeTypeException;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import com.alibaba.fastjson2.JSONObject;
import com.nfzm.service.NfzmArticleService;
import com.nfzm.dao.NfzmArticleDao;
import com.nfzm.entity.NfzmArticle;
/**
 * NfzmArticle的服务接口的实现类
 * 
 * @author 
 *
 */
@Service
@Slf4j
public class NfzmArticleServiceImpl implements NfzmArticleService {
	private final Logger LOG = LogManager.getLogger(this.getClass());

	@Autowired
	private NfzmArticleDao nfzmArticleDao;

	@Autowired
	private NfzmTermService termService;

	@Autowired
	private NfzmArticlePicDao picDao;
	// TODO 当你看到这个方法时你应该创建一个工具类做通用的方法,定义自己的返回格式化
	private static final int C200 = 200;
	private static final int C412 = 412;
	public String resultFormat(int code, Object data) {
		JSONObject result = new JSONObject();
		result.put("code", code);
		if (data != null) {
			result.put("data", data);
		}
		return result.toJSONString();
	}

	@Override
	public List<NfzmArticle> find(ArticleVO value) {
		//TODO这里可以做通过Assist做添加查询
		if(value.getPageSize()==0){
			value.setPageSize(10);
		}
		if(value.getPage()==0){
			value.setPage(1);
		}
		value.setBegin((value.getPage()-1)*value.getPageSize());
		List<NfzmArticle> result = nfzmArticleDao.selectNfzmArticleByObj(value);

		if (LOG.isDebugEnabled()) {
			LOG.debug("执行获取NfzmArticle数据集-->结果:", result);
		}
		return result;
	}

	@Override
	public List<NfzmArticle> dealData(ArticleVO value) {
		//TODO这里可以做通过Assist做添加查询
		if(value.getPageSize()==0){
			value.setPageSize(10);
		}
		if(value.getPage()==0){
			value.setPage(1);
		}
		value.setBegin((value.getPage()-1)*value.getPageSize());
		List<NfzmArticle> result = nfzmArticleDao.dealData(value);

		if (LOG.isDebugEnabled()) {
			LOG.debug("执行获取NfzmArticle数据集-->结果:", result);
		}
		return result;
	}

	@Override
	public List<NfzmArticle> findWithPics(ArticleVO value) {
		//TODO这里可以做通过Assist做添加查询
		if(value.getPageSize()==0){
			value.setPageSize(10);
		}
		if(value.getPage()==0){
			value.setPage(1);
		}
		value.setBegin((value.getPage()-1)*value.getPageSize());
		List<NfzmArticle> result = nfzmArticleDao.selectNfzmArticleByObj(value);
		for(NfzmArticle article:result){
			NfzmArticlePic query = new NfzmArticlePic();
			query.setArticleId(article.getId());
			List<NfzmArticlePic> pics = picDao.selectNfzmArticlePicByObj(query);
			article.setPics(pics);
		}
		if (LOG.isDebugEnabled()) {
			LOG.debug("执行获取NfzmArticle数据集-->结果:", result);
		}
		return result;
	}
	@Override
	public NfzmArticle findOne(String id) {
		if (id == null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("执行通过NfzmArticle的id获得NfzmArticle对象-->失败:id不能为空");
			}
			return null;
		}
		NfzmArticle result = nfzmArticleDao.selectNfzmArticleById(id);
		if (LOG.isDebugEnabled()) {
			LOG.debug("执行通过NfzmArticle的id获得NfzmArticle对象-->结果:", result);
		}
		return result;
	}

	@Override
	public NfzmArticle findOneWithPics(String id) {
		NfzmArticle result = nfzmArticleDao.selectNfzmArticleById(id);
		NfzmArticlePic query = new NfzmArticlePic();
		query.setArticleId(id);
		List<NfzmArticlePic> pics = picDao.selectNfzmArticlePicByObj(query);
		result.setPics(pics);
		return result;
	}

	@Override
	public NfzmArticle findWithOthers(String id) {
		NfzmArticle result = nfzmArticleDao.selectNfzmArticleById(id);
		if(null!=result.getNextId()){
			result.setNext(findOneWithPics(result.getNextId()));
		}
		if(null!=result.getRelateIds()){
			String[] ids = result.getRelateIds().split(",");
			ArticleVO query  = new ArticleVO();
			query.setIds(Arrays.asList(ids));
			List<NfzmArticle> list =  find(query);
			result.setRelates(list);
		}
		return result;
	}

	@Override
	public int saveNotNull(NfzmArticle value) {
		if (value == null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("执行将NfzmArticle中属性值不为null的数据保存到数据库-->失败:对象不能为空");
			}
			return -1;
		}
		int result = nfzmArticleDao.insertNotNullNfzmArticle(value);
		if (LOG.isDebugEnabled()) {
			LOG.debug("执行将NfzmArticle中属性值不为null的数据保存到数据库-->结果:", result);
		}
		return result;
	}
	@Override
	public int updateNotNullById(NfzmArticle value) {
		if (value == null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("执行通过NfzmArticle的id更新NfzmArticle中属性不为null的数据-->失败:对象为null");
			}
			return -1;
		}
		int result = nfzmArticleDao.updateNotNullNfzmArticleById(value);
		if (LOG.isDebugEnabled()) {
			LOG.debug("执行通过NfzmArticle的id更新NfzmArticle中属性不为null的数据-->结果:", result);
		}
		return result;
	}

	@Override
	public int deleteById(String id) {
		if (id == null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("执行通过NfzmArticle的id删除NfzmArticle-->失败:id不能为空");
			}
			return -1;
		}
		int result = nfzmArticleDao.deleteNfzmArticleById(id);
		if (LOG.isDebugEnabled()) {
			LOG.debug("执行通过NfzmArticle的id删除NfzmArticle-->结果:", result);
		}
		return result;
	}

	@Override
	public int saveBatch(List<NfzmArticle> list) {
		return nfzmArticleDao.insertNfzmArticleByBatch(list);
	}

	@Override
	public int setContent(NfzmArticle article) {

		String url = "https://www.infzm.com/contents/"+article.getId();
		Connection connection = Jsoup.connect(url);
		connection.header("Cookie","UM_distinctid=1916a1219dab0d-067afb26d6cd39-26001e51-144000-1916a1219dbcb9; machine_id=b81cf7c1f17f6b2a98eb0d3f62d758d1; passport_u=1724062447_4108650_78d2e37cb3cb0853a58f8c93b23c8dd8; acw_tc=2f6a1f8517241413334362007e78af0ce4c86a45b49391d8f77c7a5677c3ae; __ACCOUNT__={%22id%22:4108650%2C%22old_uid%22:null%2C%22username%22:%22165****7873%22%2C%22phone%22:%2219231219072%22%2C%22email%22:%2216535807873@infzm.com_5644%22%2C%22created_at%22:%222022-07-01%2018:54:13%22%2C%22updated_at%22:%222024-07-01%2015:38:16%22%2C%22loginname%22:%2219231219072%22%2C%22from%22:%22api%22%2C%22regip%22:%2247.106.31.140%22%2C%22regdate%22:1656672853%2C%22phone_prefix%22:%22+86%22%2C%22avatar_url%22:%22http://avatar.infzm.com/users/default.gif%22%2C%22regplatform%22:%22%22%2C%22snsplatform%22:%22%22%2C%22avatar%22:%22http://avatar.infzm.com/users/default.gif%22%2C%22member_type%22:3%2C%22expire_time%22:%222026-04-28%2015:02:35%22}; XSRF-TOKEN=eyJpdiI6IjBVOVdCZDljVkhjaGVQTFpDVEs3blE9PSIsInZhbHVlIjoiTEh2Nmt0SkRPd1Q0a1dZMTRXUHZySU92NlZkM09Fb0dcL1NmMzREckNcL0d4N29mOU55c2pqalRLSytkZEFLcTQxIiwibWFjIjoiNjcwZDRjOTdmNDQ0ZTg5ZDNiN2IxYTJhODI1ZDBhODA2NzA0NjQyZjg3YWRkMjg1YWYxMzZkODM5YmM2MTBlYSJ9; passport_session=eyJpdiI6Im9tRXc2TVYyeE44MWxEVHY4Q0hMTWc9PSIsInZhbHVlIjoicEFNTFJZNENSV0xXQUdMYmpBdkdwRDh2UTlwXC96U0FuOElhRkdaT2pjTW45UlRHQWxrREFoMzZjOFJVcXBNMk8iLCJtYWMiOiI3NmFkYWU4OWU4ZDU4ODc1OTQxZDEzNzA4YmYxNjI0NDFkMjFhNmQ5NzZmOTgzYTNhY2FhMDVmMTY2YWU4MjY5In0%3D; CNZZDATA1277810324=1800990360-1724061457-https%253A%252F%252Fpassport.infzm.com%252F%7C1724141379");
		connection.header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36");
		/*connection.header("","");
		connection.header("","");
		connection.header("","");
		connection.header("","");
		connection.header("","");*/
		Document document = null;
		Element element =null;
		String content = null;
		try {
			document = connection.get();
			Elements elements = document.getElementsByClass("nfzm-content__fulltext");
			if(elements.size()>0){
				element = elements.get(0);
				content = element.html();
				//article.setContent(content);
				//log.info("正文取到了" +article.getId());
			}else{
				//log.info("elements没有" +article.getId());
				article.setContent("合集");
			}

			Elements terms = document.getElementsByClass("nfzm-content__term");

			if(terms.size()>0){
				String termName = terms.get(0).text();
				//String termId = termService.findIdByName(termName);
				//article.setTermId(termId);
				//log.info("分类取到了");
			}

			Elements nextContents = document.getElementsByClass("next_content");
			if(nextContents.size()>0){
				Element nextContent = nextContents.get(0);
				Elements as = nextContent.select("a");
				if(as.size()>0){
					String nextUrl = as.get(0).attr("href");
					int begin = nextUrl.indexOf("s");
					int end = nextUrl.indexOf("?");
					String nextId = nextUrl.substring(begin+2,end);
					article.setNextId(nextId);
					//log.info("下一篇取到了");
				}
			}else{
				article.setNextId("0");
			}

			Elements importants = document.getElementsByClass("ui-important");
			if(importants.size()>0){
				Element important = importants.get(0);
				Elements lias = important.select("a");
				StringBuilder builder = new StringBuilder();
				for(int i=0;i<lias.size();i++){
					String relateUrl = lias.get(i).attr("href");
					int begin = relateUrl.indexOf("s");
					int end = relateUrl.indexOf("?");
					String relateId = relateUrl.substring(begin+2,end);
					builder.append(relateId);
					if(i<lias.size()-1){
						builder.append(",");
					}
				}
				article.setRelateIds(builder.toString());
			}


			return updateNotNullById(article);
		} catch (UnsupportedMimeTypeException e) {
			log.error("不支持的内容"+article.getId(),e);
			article.setContent("视频");
			article.setNextId("0");
			return updateNotNullById(article);
			//throw new RuntimeException(e);
		}catch (Exception e){
			log.error("出错了"+article.getId(),e);
		}

		return 0;
	}


}